<?php

class Ext_Utils_Execute
{

    /**
     * Funcion utilidad para ejecutar
     *
     * @param   string  $command    el comando que hay que ejecutar.
     * @param   string  $stdInTxt   buffer a mandar por stdin
     * @param   string  $cwd        current work directory    
     * @param   string  $env        environment
     * @return  string  $ret        el buffer que devolvio el comando
     */
    static public function Execute( $command, $stdInTxt = null, $cwd = "/tmp", $env = array() )
    {

        $descriptorspec = array( 
                        0 => array( 
                                        "pipe", 
                                        "r" 
                        ), 
                        1 => array( 
                                        "pipe", 
                                        "w" 
                        ), 
                        2 => array( 
                                        "pipe", 
                                        "w" 
                        ) 
        );
        $pipes = array();
        $process = proc_open( $command, $descriptorspec, $pipes, $cwd, $env );
        
        if ( ! $process || ! is_resource( $process ) ) {
            throw new Exception( "Error executing command" );
        }
        
        if ( $stdInTxt != null ) {
            fwrite( $pipes[ 0 ], $stdInTxt );
        }
        fclose( $pipes[ 0 ] );
        $stdOut = htmlentities( stream_get_contents( $pipes[ 1 ] ) );
        fclose( $pipes[ 1 ] );
        
        $stdErr = htmlentities( stream_get_contents( $pipes[ 2 ] ) );
        fclose( $pipes[ 2 ] );
        
        $return_value = proc_close( $process );
        if ( $return_value != 0 ) {
            throw new Exception( "Error number $return_value executing command, error : $stdErr" );
        }
        if ( ! empty( $stdErr ) ) {
            throw new Exception( "Error executing command: $stdErr" );
        }
        
        return $stdOut;
    }
}


